/*
 * @Author: 周凯
 * @Date: 2020-10-09 08:42:53
 * @LastEditTime: 2020-10-09 08:46:55
 */
const bodyParser = require("body-parser");
const express = require("express");
const app = express();

const router = express.Router();

const port = 3000;

app.use(bodyParser.json());

global.store = {
  count: 0,
  status: false,
  ip: "192.168.0.201",
};

router.use(async (req, res, next) => {
  console.log(req.url);
  console.log(req.body);
  console.log("req中间件");
  if (req.url === "/set") {
    global.store.status = true;
    const r = await test();
    console.log(r);
    // res.send({
    //     data: r + '- req中间件',
    //     code: 1
    // })
    global.store.status = false;
    next();
  } else {
    const storeIterval = setInterval(() => {
      if (!global.store.status) {
        next();
        clearInterval(storeIterval);
      }
    }, 1);
  }
});

router.get("/", (req, res) => res.send("hello world"));

router.post("/set", (req, res) => {
  // console.log(req, 'req');
  res.send({
    data: "1",
    code: 0,
  });
});

router.get("/get", async (req, res) => {
  console.log(req.query, "req");
  try {
    const r = await test1();
    res.send({
      data: r,
      code: 0,
    });
  } catch (err) {}
});

function test() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("这个是测试数据req");
    }, 10000);
  });
}

function test1() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("这个是测试数据get");
    }, 1000);
  });
}

app.use(router);

app.listen(port, () => {
  console.log("启动端口3000");
});

function setPlcData() {
  var s7client = new snap7.S7Client();
  s7client.ConnectTo("192.168.0.201", 0, 1, function (err) {
    if (err)
      return console.log(
        " >> Connection failed. Code #" + err + " - " + s7client.ErrorText(err)
      );

    // Read the first byte from PLC process outputs...
    s7client.DBRead(1, 0, 20, function (err, res) {
      if (err)
        return console.log(
          " >> ABRead failed. Code #" + err + " - " + s7client.ErrorText(err)
        );

      // ... and write it to stdout
      console.log(res.toJSON().data, Date.now());
    });
  });
  s7client.Disconnect();
}
